package run.iget.admin.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

import cn.hutool.core.collection.CollectionUtil;
import run.iget.admin.system.constant.AdminSystemConst;
import run.iget.admin.system.entity.RolePermission;
import run.iget.admin.system.entity.table.RolePermissionTableDef;
import run.iget.admin.system.mapper.RolePermissionMapper;
import run.iget.admin.system.service.RolePermissionService;
import run.iget.framework.common.util.ExceptionThrowUtils;

/**
 * <p>
 * 角色-权限关联表 服务实现类
 * </p>
 *
 * @author 大周
 * @since 2022-02-07
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission>
        implements RolePermissionService {

    @Override
    public void relationPermissions(Long roleId, List<Long> permissionIds) {
        ExceptionThrowUtils.ofNull(roleId, "角色id不可为空");
        // 删除角色对应的权限
        this.remove(RolePermissionTableDef.ROLE_PERMISSION.ROLE_ID.eq(roleId));
        // 批量插入新的权限
        if (CollectionUtil.isNotEmpty(permissionIds)) {
            List<RolePermission> rolePermissionList = new ArrayList<>(permissionIds.size());
            RolePermission rolePermission = null;
            for (Long permissionId : permissionIds) {
                rolePermission = new RolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermissionList.add(rolePermission);
            }
            this.saveBatch(rolePermissionList);
        }
    }

    @Override
    public List<Long> listPermissionIds(Long roleId) {
        ExceptionThrowUtils.ofNull(roleId, "角色id不可为空");
        QueryWrapper queryWrapper = QueryWrapper.create().select(RolePermissionTableDef.ROLE_PERMISSION.PERMISSION_ID)
                .where(RolePermissionTableDef.ROLE_PERMISSION.ROLE_ID.eq(roleId));
        return this.listAs(queryWrapper, Long.class);
    }

    @Override
    public void relationNewPermission(Long permissionId) {
        ExceptionThrowUtils.ofNull(permissionId, "权限id不可为空");
        RolePermission rolePermission = new RolePermission();
        rolePermission.setPermissionId(permissionId);
        rolePermission.setRoleId(AdminSystemConst.ADMIN_ROLE_ID);
        this.save(rolePermission);
    }
}
